package com.sharing.service;

import com.sharing.common.Page;
import com.sharing.common.Result;
import com.sharing.domain.User;
import com.sharing.domain.UserProduction;
import com.sharing.domain.UserTalk;
import com.sharing.mapper.UserMapper;
import com.sharing.mapper.UserProductionMapper;
import com.sharing.mapper.UserTalkMapper;
import com.sharing.util.StringUtils;
import com.sharing.util.ThreadLocalStorage;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;

import javax.xml.ws.handler.LogicalHandler;
import java.net.Inet4Address;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

/**
 * @author Du
 * @version 1.0
 * @description TODO
 * @date 2023/4/4 21:39
 */
@Service
public class UserTalkService {
    @Autowired
    private UserTalkMapper userTalkMapper;

    @Autowired
    private UserMapper userMapper;

    public Result<List<UserTalk>> selectUserTalksBySenderIdAndAcceptorId(Integer senderId, Integer acceptorId, Integer days) {
        // 校验一：对传入两个用户id进行校验
        User senderUser = userMapper.selectUserById(senderId);
        if (senderId == null) {
            return new Result<>(1, "发送用户不存在");
        }
        User acceptorUser = userMapper.selectUserById(acceptorId);
        if (acceptorUser == null) {
            return new Result<>(1, "接收用户不存在");
        }

        // 校验二：当前登录用户仅仅是二者其一才允许进一步访问
        User loginUser = ThreadLocalStorage.getUser();
        if (loginUser == null) {
            synchronized (this) {
                if (loginUser == null) {
                    Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
                    loginUser = userMapper.selectUserByUserName(authentication.getName());
                    ThreadLocalStorage.setUser(loginUser);
                }
            }
        }
        if (loginUser.getId() != senderId && loginUser.getId() != acceptorId) {
            return new Result<>(1, "不是该对话参与者，禁止访问");
        }

        // 通过mapper持久层从数据库查询数据
        List<UserTalk> userTalks = userTalkMapper.selectUserTalksBySenderIdAndAcceptorId(senderId, acceptorId, days);

        return new Result<>(0, userTalks);
    }

    /**
     * 通过两个用户id查询他们之间对话记录的业务层方法
     * @param ids
     * @param days
     * @return
     */
    public Result<List<UserTalk>> selectUserTalksByIds(List<Integer> ids, Integer days) {
        // 校验ids
        if (ids == null || ids.size() != 2 || ids.get(0) == ids.get(1)) {
            return new Result<>(1, "参数传入不当");
        }

        // 查询以ids.get(0)作为发送用户，ids.get(1)作为接收用户之间的对话
        List<UserTalk> userTalks1 = selectUserTalksBySenderIdAndAcceptorId(ids.get(0), ids.get(1), days).getData();

        // 查询以ids.get(1)作为发送用户，ids.get(0)作为接收用户之间的对话
        List<UserTalk> userTalks2 = selectUserTalksBySenderIdAndAcceptorId(ids.get(1), ids.get(0), days).getData();

        // 按照时间顺序拼接
        List<UserTalk> userTalks = new ArrayList<>();

        int i = 0, j = 0;
        while (i < userTalks1.size() && j < userTalks2.size()) {
            if (StringUtils.compareStrings(userTalks1.get(i).getCreateDate(), userTalks2.get(j).getCreateDate())) {
                userTalks.add(userTalks1.get(i));
                i++;
            } else {
                userTalks.add(userTalks2.get(j));
                j++;
            }
        }

        while (i < userTalks1.size()) {
            userTalks.add(userTalks1.get(i));
            i++;
        }

        while (j < userTalks2.size()) {
            userTalks.add(userTalks2.get(j));
            j++;
        }

        return new Result<>(0, userTalks);
    }

    /**
     * 新增对话的业务层方法
     * @param userTalk
     * @return
     */
    public Result<UserTalk> insertUserTalk(UserTalk userTalk) {
        if (userTalk == null || userTalk.getAcceptorId() == null || userTalk.getContent() == null) {
            return new Result<>(1, "传入参数不当");
        }

        // 获取当前登录用户
        User loginUser = ThreadLocalStorage.getUser();
        if (loginUser == null) {
            synchronized (this) {
                if (loginUser == null) {
                    Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
                    loginUser = userMapper.selectUserByUserName(authentication.getName());
                    ThreadLocalStorage.setUser(loginUser);
                }
            }
        }

        // 为防止其他用户代替某一用户发送信息而进行的校验
        if (userTalk.getSenderId() != null && userTalk.getSenderId() != loginUser.getId()) {
            return new Result<>(1, "当前用户没有权限发送此次对话信息");
        }
        userTalk.setSenderId(loginUser.getId());

        Integer rows = userTalkMapper.insertUserTalk(userTalk);

        if (rows != 1) {
            return new Result<>(1, "发送失败，请稍后重试");
        }

        return new Result<>(0, userTalk);
    }

    /**
     * 删除对话的业务层方法
     * @param id
     * @return
     */
    public Result<Integer> deleteUserTalkById(Integer id) {
        // 校验该对话记录是否存在
        UserTalk userTalk = userTalkMapper.selectUserTalkById(id);
        if (userTalk == null) {
            return new Result<>(1, "该对话记录不存在或已删除");
        }

        // 获取当前登录用户
        User loginUser = ThreadLocalStorage.getUser();
        if (loginUser == null) {
            synchronized (this) {
                if (loginUser == null) {
                    Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
                    loginUser = userMapper.selectUserByUserName(authentication.getName());
                    ThreadLocalStorage.setUser(loginUser);
                }
            }
        }

        if (!Objects.equals(loginUser.getId(), userTalk.getSenderId())) {
            return new Result<>(1, "您没有删除该对话的权限");
        }

        Integer rows = userTalkMapper.deleteUserTalkById(id);

        if (rows != 1) {
            return new Result<>(1, "删除失败，请稍后重试");
        }

        return new Result<>(0, rows);
    }
}
